<template>
  <div class="query-form">
    <el-form ref="formRef" :model="queryForm" :rules="rules" inline>
      <el-form-item label="是否在职" prop="is_leave" style="width: 200px">
        <el-select v-model="queryForm.is_leave">
          <el-option label="离职" value="0" />
          <el-option label="在职" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="月" prop="month">
        <el-date-picker
          style="width: 140px"
          v-model="queryForm.month"
          :clearable="false"
          type="month"
          value-format="YYYY-MM"
        />
      </el-form-item>

      <el-form-item label="根据类型查询" prop="type">
        <!-- :disabled="isDimission" -->
        <el-select v-model="queryForm.type">
          <el-option label="全部" value="0" />
          <el-option label="办公室全职" value="1" />
          <el-option label="门店全职" value="3" />
          <el-option label="高级店长" value="4" />
          <!-- <el-option label="全部" value="all" />
          <el-option label="清洁工" value="cleaner" />
          <el-option label="办公室" value="office" />
          <el-option label="门店全职" value="fullTimeEmployee" />
          <el-option label="门店兼职" value="partTimeEmployee" />
          <el-option label="高级店长" value="superManager" /> -->
        </el-select>
      </el-form-item>

      <el-form-item label="门店" prop="shopId">
        <shop-cascadar
          :disabled="!isFlack"
          v-model:shop-id="queryForm.shopId"
          type="shopId"
          :flacktype="queryForm.type"
          :is_leave="queryForm.is_leave"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQueryClick">查询</el-button>
        <el-button type="primary" @click="handleExportClick">导出</el-button>
        <!-- <el-button type="primary" @click="handlePrintClick">打印</el-button> -->
      </el-form-item>
    </el-form>
  </div>
  <el-table
    v-loading="isLoading"
    :cell-style="cellStyle"
    height="76vh"
    :data="attendances"
    border
  >
    <el-table-column v-if="RconputeSalary" fixed label="重算薪资" width="100">
      <template #default="{ row }">
        <el-button type="primary" size="small" @click="handleXinZi(row)"
          >重算薪资</el-button
        >
      </template>
    </el-table-column>
    <el-table-column fixed label="ID" prop="userid" />
    <el-table-column fixed label="人员名称" prop="username" />
    <el-table-column fixed label="人员部门" prop="dept_name" />
    <el-table-column label="人员门店" prop="shop_name" />

    <el-table-column label="入职日期" prop="timeOfEntry" />
    <el-table-column label="身份证号" prop="id_card" />
    <el-table-column label="平均月薪" prop="avarage_salarys" />
    <el-table-column label="当月总天数" prop="daysofmonth" />
    <el-table-column label="应出勤天数" prop="daysofplan" />
    <el-table-column label="月薪" prop="basic_month" />
    <el-table-column label="日薪" prop="basic_days" />
    <el-table-column label="应发工资" prop="totall_salarys" />

    <el-table-column label="迟到次数" prop="late_nums" />
    <el-table-column label="迟到时长" prop="late_time" />
    <el-table-column label="早退时长" prop="early_time" />
    <el-table-column label="早退次数" prop="early_nums" />
    <el-table-column label="缺卡次数" prop="miss_nums" />
    <el-table-column label="病假次数" prop="bingjia_nums" />
    <el-table-column label="事假次数" prop="shijia_nums" />
    <el-table-column label="补卡次数" prop="buka_nums" />
    <el-table-column label="加班时长" prop="jiaban_times" />
    <el-table-column label="补钟时长" prop="buzhong_times" />

    <!-- 动态生成薪资项目列 -->
    <template v-for="(item, keys) in salaryColumns" :key="item">
      <el-table-column :label="item.name" :index="item.type">
        <template #default="scope">
          <div
            @click="handleCellClick(scope.row, item.name)"
            style="height: 70px; line-height: 70px; width: 70px"
          >
            <span>
              {{ getSalaryValue(scope.row.salary, item.name) }}
            </span>
          </div>
        </template>
      </el-table-column>
    </template>
  </el-table>
  <div class="pagination">
    <el-pagination
      v-model:current-page="queryForm.pageNumber"
      v-model:page-size="queryForm.pageSize"
      :page-count="totalPages"
      :page-sizes="[10, 20, 50, 100]"
      background
      layout="prev, pager, next, jumper, sizes"
      @change="handlePaginationChange"
    />
  </div>

  <el-drawer v-model="isViewDrawerShow" :show-close="true" size="450" :title="handleName">
    <el-form
      ref="formRefsd"
      style="max-width: 100%"
      :model="selecteattendances"
      label-width="auto"
      :rules="rulessd"
      class="demo-ruleForm"
    >
      <el-form-item label="ID" prop="id">
        <el-input :disabled="true" v-model.number="selecteattendances.id" type="text" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input :disabled="true" v-model.number="selecteattendances.name" type="text" />
      </el-form-item>
      <el-form-item label="金额" prop="salary_nums">
        <el-input v-model.number="selecteattendances.salary_nums" type="number" />
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input v-model.number="selecteattendances.note" :rows="5" type="textarea" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(formRefsd)">提交修改</el-button>
        <el-button @click="isViewDrawerShow = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script lang="ts" setup>
import { computed, CSSProperties, ref, watch, reactive } from "vue";
import {
  getFullTimePayroll,
  putFullTimePayroll,
  getKaoqinBackcalmoney,
} from "@/api/FullTimePayroll";
import { ElForm, ElMessage, FormInstance, FormRules } from "element-plus";
import { isAxiosError } from "axios";
import { utils, writeFile } from "xlsx";
import print from "print-js";
import ShopCascadar from "@/components/cascader/ShopCascadar.vue";
import { formatDateToYearAndMonth } from "@/utils/date";

const attendances = ref<any[]>([]);
//修改框的title
const handleName = ref("");

//重算考勤要查的年月
const monthDay = ref("");

const selecteattendances = ref<{
  id?: string;
  salary_nums?: string;
  note?: string;
  name?: string;
}>({
  id: "",
  salary_nums: "",
  note: "",
  name: "",
});

const totalPages = computed(() => attendances.value[0]?.total_pages);
const isViewDrawerShow = ref(false);
const isLoading = ref(false);

//控制重算薪资按钮的显示与隐藏
const RconputeSalary = ref(false);

// 获取所有唯一的薪资项目列
const salaryColumns = computed(() => {
  if (!attendances.value.length) return [];
  // 从第一行数据中获取所有薪资项目
  const ArrayItem = [
    ...new Set(
      attendances.value.flatMap((item1) => {
        return item1.salary.map((itemSalary: any) => {
          return {
            name: itemSalary.name,
            type: itemSalary.type,
          };
        });
      })
    ),
  ];
  const uniqueItemsMap = new Map();

  ArrayItem.forEach((item) => {
    // 使用 name 和 type 的组合作为唯一键
    const key = `${item.name}-${item.type}`;
    uniqueItemsMap.set(key, item);
  });

  // 将 Map 转换回数组
  return Array.from(uniqueItemsMap.values()) || [];


});

const formRefsd = ref<FormInstance>();

const submitForm = (formEl: {
  validate: (arg0: (valid: any) => Promise<void>) => void;
}) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      const res = await putFullTimePayroll({
        id: selecteattendances.value.id,
        salary_nums: selecteattendances.value.salary_nums,
        note: selecteattendances.value.note,
      });
      if (res.code == "200") {
        ElMessage.success("修改成功");
        isViewDrawerShow.value = false;
        getData();
      } else {
        ElMessage.error("修改错误");
      }
    } else {
      ElMessage.error("表单校验错误");
    }
  });
};

const rulessd = reactive({
  id: [{ required: true, message: "请输入ID", trigger: "blur" }],
  name: [{ required: true, message: "请输入ID", trigger: "blur" }],
  salary_nums: [{ required: true, message: "请输入金额", trigger: "blur" }],
  note: [{ required: true, message: "请输入备注", trigger: "blur" }],
});

// 获取对应的薪资值
const getSalaryValue = (salary: any[], key: any) => {
  const salary_nums_item = salary.find((items) => {
    if (items.name == key) {
      return items;
    }
  });
  if (salary_nums_item) {
    return salary_nums_item?.salary_nums;
  } else {
    return "0";
  }

};

// 打开修改框
function handleCellClick(row: any, key: any) {
  handleName.value = `姓名：${row.username}`;
  // 通过 switch 语句判断只有在点击日期列时才打开抽屉展示考勤状
  const salary_nums_item = row.salary.find((items: { name: any }) => {
    if (items.name == key) {
      return items;
    }
  });
  console.log(salary_nums_item);

  if (salary_nums_item) {
    selecteattendances.value = salary_nums_item;
    isViewDrawerShow.value = true;
  } else {
    ElMessage.warning("该员工无这项权限");
    selecteattendances.value = {};
  }

  // selecteattendances.value = row.salary[key];
}

const queryForm = ref<{
  type: "0" |"1" | "3" | "4" | null;
  attendanceGroupId: number | undefined;
  shopId?: number;
  month: string;
  pageNumber: number;
  pageSize: number;
  is_leave: "0" | "1";
}>({
  type: "0",
  attendanceGroupId: undefined,
  month: formatDateToYearAndMonth(new Date()),
  pageNumber: 1,
  pageSize: 10,
  is_leave: "1",
});
const formRef = ref<InstanceType<typeof ElForm>>();

  // 表单校验规则
const rules = ref<FormRules>({
  month: [
    {
      required: true,
      message: "月不能为空",
      trigger: "change",
    },
  ],
  is_leave: [
    {
      required: true,
      message: "请选择查询类型",
      trigger: "change",
    },
  ],
  type: [
    {
      required: true,
      message: "请选择查询类型",
      trigger: "change",
    },
  ],
});

const isFlack = computed(() => {
  let flacks = false;
  if (queryForm.value.type == "3" && queryForm.value.is_leave == "1") {
    flacks = true;
  } else {
    flacks = false;
  }

  return flacks;
});


//监听是不是选中离职
watch(
  () => queryForm.value.is_leave,
  (newval, ollval) => {
    queryForm.value.type = "1";
  }
);



// 根据选项进行监听然后个表单赋予校验方法
watch(
  () => queryForm.value.type,
  (newValue, _oldValue) => {
    switch (newValue) {
      case "0": {
        queryForm.value.shopId = undefined;
        rules.value.shopId = undefined;
        break;
      }
      case "1": {
        queryForm.value.shopId = undefined;
        rules.value.shopId = undefined;
        break;
      }
      case "3": {
        if (queryForm.value.is_leave == "1") {
          rules.value.shopId = [
            {
              required: true,
              message: "门店不能为空",
              trigger: "change",
            },
          ];
        }

        break;
      }
      case "4": {
        queryForm.value.shopId = undefined;
        rules.value.shopId = undefined;
        break;
      }
    }
  }
);


// 表格赋予颜色
function cellStyle({
  row,
  column,
}: {
  row: { salary: any };
  column: {
    [x: string]: string;
    label: string;
  };
}) {
  // console.log(row);
  // console.log(column.index);

  // const items = row.salary[column.index];
  const style: CSSProperties = {};
  if (column.index) {
    if (column.index == "add_items") {
      style.cursor = "pointer";
      style.backgroundColor = "#67C23A";
      style.color = "white";
      style.fontSize = "18px";
    } else if (column.index == "others") {
      style.cursor = "pointer";
      style.backgroundColor = "#e6a23c";
      style.color = "white";
      style.fontSize = "18px";
    } else if (column.index == "deduct_items") {
      style.cursor = "pointer";
      style.backgroundColor = "#f56c6c";
      style.color = "white";
      style.fontSize = "18px";
    }
  }

  return style;
}


// 请求数据
async function getData() {
  if (isLoading.value == false) {
    isLoading.value = true;
  }

  RconputeSalary.value = false;

  switch (queryForm.value.type) {
    case "0": {
      const { data } = await getFullTimePayroll({
        month: queryForm.value.month,
        employee_type: "0",
        page: queryForm.value.pageNumber,
        per_page: queryForm.value.pageSize,
        is_leave: queryForm.value.is_leave,
      });
      if (data !== undefined) {
        monthDay.value = queryForm.value.month;
        if (queryForm.value.is_leave == "0") {
          RconputeSalary.value = true;
        }
        attendances.value = data;
        isLoading.value = false;
      } else {
        ElMessage.error("查询失败");
        isLoading.value = false;
      }
      break;
    }
    case "1": {
      const { data } = await getFullTimePayroll({
        month: queryForm.value.month,
        employee_type: "1",
        page: queryForm.value.pageNumber,
        per_page: queryForm.value.pageSize,
        is_leave: queryForm.value.is_leave,
      });
      if (data !== undefined) {
        monthDay.value = queryForm.value.month;
        if (queryForm.value.is_leave == "0") {
          RconputeSalary.value = true;
        }
        attendances.value = data;
        isLoading.value = false;
      } else {
        ElMessage.error("查询失败");
        isLoading.value = false;
      }
      break;
    }
    case "3": {
      const { data } = await getFullTimePayroll({
        shop_id: queryForm.value.shopId,
        month: queryForm.value.month,
        employee_type: "3",
        page: queryForm.value.pageNumber,
        per_page: queryForm.value.pageSize,
        is_leave: queryForm.value.is_leave,
      });
      if (data !== undefined) {
        monthDay.value = queryForm.value.month;
        if (queryForm.value.is_leave == "0") {
          RconputeSalary.value = true;
        }
        attendances.value = data;
        isLoading.value = false;
      } else {
        ElMessage.error("查询失败");
        isLoading.value = false;
      }
      break;
    }
    case "4": {
      const { data } = await getFullTimePayroll({
        month: queryForm.value.month,
        employee_type: "4",
        page: queryForm.value.pageNumber,
        per_page: queryForm.value.pageSize,
        is_leave: queryForm.value.is_leave,
      });
      if (data !== undefined) {
        monthDay.value = queryForm.value.month;
        if (queryForm.value.is_leave == "0") {
          RconputeSalary.value = true;
        }
        attendances.value = data;
        isLoading.value = false;
      } else {
        ElMessage.error("查询失败");
        isLoading.value = false;
      }
      break;
    }
    default: {
      ElMessage.error("表单错误");
      isLoading.value = false;
    }
  }
}

async function handleXinZi(row: any) {
  const res: { code?: any; msg?: any; date?: any } = await getKaoqinBackcalmoney({
    userid: row.userid,
    cal_month: monthDay.value,
  });
  if (res.code == "200") {
    ElMessage.success(res.msg);
  } else {
    ElMessage.error(res.msg);
  }
}


//数据打印
function handleExportClick() {
  if (attendances.value.length > 0) {
    function transformSalary(inputArray: any[]) {
      return inputArray.map((input: { [x: string]: any; salary: any[] }) => {
        // 创建一个新的对象，开始时复制输入对象的所有属性
        const result = {
          ID: input.userid,
          人员名称: input.username,
          人员部门: input.dept_name,
          人员门店: input.shop_name,
          入职日期: input.timeOfEntry,
          身份证号: input.id_card,
          平均月薪: input.avarage_salarys,
          当月总天数: input.daysofmonth,
          应出勤天数: input.daysofplan,
          月薪: input.basic_month,
          日薪: input.basic_days,
          应发工资: input.totall_salarys,

          迟到次数: input.late_nums,
          迟到时长: input.late_time,
          早退时长: input.early_time,
          早退次数: input.early_nums,
          缺卡次数: input.miss_nums,
          病假次数: input.bingjia_nums,
          事假次数: input.shijia_nums,
          补卡次数: input.buka_nums,
          加班时长: input.jiaban_times,
          补钟时长: input.buzhong_times,
        };

        // 移除原有的salary数组
        // delete result.salary;

        // 遍历salary数组，将每个元素按要求添加到结果对象中
        input.salary.forEach((item: { name: any; salary_nums: any }) => {
          const fieldName = item.name; // 使用"name"作为新字段名
          const value = item.salary_nums; // 使用"salary_nums"作为值
          result[fieldName] = value;
        });

        return result;
      });
    }
    let attendancesxiugai = transformSalary(attendances.value);

    const workBook = utils.book_new();
    const workSheet = utils.json_to_sheet(attendancesxiugai);
    utils.book_append_sheet(workBook, workSheet);
    writeFile(workBook, "output.xlsx");
  } else {
    ElMessage.error("没有数据可以导出");
  }
}


// 请求数据前表单校验
async function handleQueryClick() {
  formRef.value?.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        await getData();
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      switch (queryForm.value.type) {
        case "1": {
          ElMessage.error("请选择查询类型、月份");
          break;
        }
        case "3": {
          ElMessage.error("请选择查询类型、门店、月份");
          break;
        }
        case "4": {
          ElMessage.error("请选择查询类型、月份");
          break;
        }
        default: {
          ElMessage.error("表单校验错误");
          break;
        }
      }
    }
  });
}

async function handlePaginationChange() {
  await getData();
}
</script>

<style lang="scss" scoped>
.query-form {
  .el-select {
    --el-select-width: 240px;
  }
}

.pagination {
  margin-top: 20px;
}

.add_items {
  text-align: center;
  background: rgb(49, 158, 49);
  cursor: pointer;
  width: 100%;
  height: 100%;
  color: white;
}
.others {
  background-color: rgb(212, 212, 39);
  text-align: center;
  cursor: pointer;
  width: 100%;
  height: 100%;
  color: white;
}
.deduct_items {
  background-color: rgb(49, 158, 49);
  text-align: center;
  cursor: pointer;
  width: 100%;
  height: 100%;
  color: white;
}
</style>
